<template>
  <el-dialog
    v-model="props.modelValue"
    width="1000px"
    :show-close="false"
    :close-on-click-modal="false"
    :before-close="handleClose"
  >
    <template #header="{ close, titleId, titleClass }">
      <div class="my-header">
        <h4
          :id="titleId"
          :class="titleClass"
        >
          {{ t(`dockRepair.btn11`) }}
        </h4>
        <img
          src="@/assets/img/icon_guanbi.png"
          @click="close"
          class="close"
        />
      </div>
    </template>

    <div class="step1">
      <el-tabs
        v-model="activeName"
        @tab-change="tabChange"
      >
        <el-tab-pane
          :label="item.projectName"
          :name="index"
          v-for="(item, index) in tabData"
          :disabled="activeStep === 1"
        >
        </el-tab-pane>
      </el-tabs>

      <div class="title">{{ t('dockRepair.step2page.steelStructure.tit4') }}：</div>
      <div class="select">
        <div class="item">
          <div class="con flexsc">
            <div
              :class="['li', 'mr-1', { active: s1ActiveList.includes(index) }]"
              v-for="(item, index) in s1"
              :key="index"
              @click="handleSelect(index, s1ActiveList)"
            >
              {{ item.projectName }}
            </div>
          </div>
        </div>

        <div class="item">
          <div class="con flexsc">
            <div
              :class="['li', 'mr-1', { active: s2ActiveList.includes(index) }]"
              v-for="(item, index) in s2"
              :key="index"
              @click="handleSelect(index, s2ActiveList)"
            >
              {{ item.projectName }}
            </div>
          </div>
        </div>
      </div>

      <div class="res mt-2 flexsc nowrap">
        <div class="mr-1">{{ t('dockRepair.step2page.valve.res') }}：</div>
        <el-input
          v-model="resValue"
          :disabled="activeStep === 1"
        ></el-input>
        <img
          src="@/assets/img/icon_bianji.png"
          class="ml-1 mr-3"
        />
        <el-button
          type="primary"
          @click="handleNext"
          :disabled="activeStep === 1"
        >
          {{ t('confirmText') }}
        </el-button>
      </div>

      <div
        class="res mt-2 flexsc nowrap"
        style="margin-top: 2px !important"
      >
        <div
          class="mr-1"
          style="visibility: hidden"
        >
          {{ t('dockRepair.step2page.valve.res') }}：
        </div>
        <el-input
          v-model="resValue2"
          :disabled="activeStep === 1"
        ></el-input>
        <img
          src="@/assets/img/icon_bianji.png"
          class="ml-1 mr-3"
        />
        <el-button
          type="primary"
          :disabled="activeStep === 1"
          style="visibility: hidden"
        >
          {{ t('confirmText') }}
        </el-button>
      </div>
    </div>

    <div class="step2">
      <el-form :disabled="activeStep === 0">
        <div class="select flexsc mt-2">
          <div class="item">
            <div class="title">{{ t('dockRepair.step2page.steelStructure.tit5') }}</div>
            <div class="con flexsc">
              <div
                :class="['li', 'mr-1', { active: index === activeType.index }]"
                v-for="(item, index) in typeList"
                :key="index"
                @click="handleSelect_type(item, index)"
              >
                {{ t(item) }}
              </div>
            </div>
          </div>
        </div>
        <!--  -->
        <div :class="[locale, 'main', 'mt-2']">
          <!-- '钢板' -->
          <template v-if="activeType.index === 0">
            <div class="form type1">
              <div class="grid-4">
                <div class="item flexsc">
                  <div class="label">{{ t('dockRepair.step2page.steelStructure.l1') }}</div>
                  <el-input-number
                    v-model="formData.aaa"
                    placeholder=""
                    :min="0"
                    :controls="false"
                  >
                  </el-input-number>
                  <div class="append">mm</div>
                </div>

                <div class="item flexsc">
                  <div class="label">{{ t('dockRepair.step2page.pipeline.l2') }}</div>
                  <el-input-number
                    v-model="formData.bbb"
                    placeholder=""
                    :min="0"
                    :controls="false"
                  >
                  </el-input-number>
                  <div class="append">m</div>
                </div>

                <div class="item flexsc">
                  <div class="label">{{ t('dockRepair.step2page.steelStructure.l2') }}</div>
                  <el-input-number
                    v-model="formData.ccc"
                    placeholder=""
                    :min="0"
                    :controls="false"
                  >
                  </el-input-number>
                  <div class="append">m</div>
                </div>

                <div class="item flexsc">
                  <div class="label">{{ t('dockRepair.step2page.steelStructure.l3') }}</div>
                  <el-input-number
                    v-model="requireCount"
                    placeholder=""
                    :min="0"
                    :precision="1"
                    :controls="false"
                  >
                  </el-input-number>
                  <div class="append">kg</div>
                </div>
              </div>
            </div>
            <div class="select flexsc mt-2">
              <div class="item">
                <div class="con flexsc">
                  <div
                    :class="['li', 'mr-1', { active: activeModel.some((a) => a.index === index) }]"
                    v-for="(item, index) in modelList"
                    :key="index"
                    @click="handleSelect_model(item, index)"
                  >
                    {{ item.isT ? t(item.val) : item.val }}
                  </div>
                </div>
              </div>
            </div>
          </template>

          <!-- '角钢', '方钢','槽钢', '球扁钢' -->
          <template v-if="[1, 2, 5, 6].includes(activeType.index)">
            <div class="form">
              <div class="grid-2">
                <div class="item flexsc">
                  <div class="label">{{ t('dockRepair.step2page.steelStructure.l4') }}</div>
                  <div>
                    <el-input-number
                      v-model="formData.aaa"
                      placeholder=""
                      :min="0"
                      :controls="false"
                    >
                    </el-input-number>
                    <span>*</span>
                    <el-input-number
                      v-model="formData.bbb"
                      placeholder=""
                      :min="0"
                      :controls="false"
                    >
                    </el-input-number>
                  </div>
                  <div class="append">mm</div>
                </div>

                <div class="item flexsc">
                  <div class="label">{{ t('dockRepair.step2page.pipeline.l2') }}</div>
                  <el-input-number
                    v-model="requireCount"
                    placeholder=""
                    :min="0"
                    :controls="false"
                  >
                  </el-input-number>
                  <div class="append">m</div>
                </div>
              </div>
            </div>
          </template>

          <!-- '圆钢', '钢管' -->
          <template v-if="[3, 4].includes(activeType.index)">
            <div class="form">
              <div class="grid-3">
                <div class="item flexsc">
                  <div class="label">{{ t('dockRepair.step2page.pipeline.l1') }}</div>
                  <el-input-number
                    v-model="formData.aaa"
                    placeholder=""
                    :min="0"
                    :controls="false"
                  >
                  </el-input-number>
                  <div class="append">mm</div>
                </div>

                <div class="item flexsc">
                  <div class="label">{{ t('dockRepair.step2page.pipeline.l2') }}</div>
                  <el-input-number
                    v-model="requireCount"
                    placeholder=""
                    :min="0"
                    :controls="false"
                  >
                  </el-input-number>
                  <div class="append">m</div>
                </div>
              </div>
            </div>
          </template>
        </div>

        <div class="bottom mt-2 flexsc nowrap">
          <div>{{ t('dockRepair.step2page.valve.res2') }}：</div>
          <el-input v-model="sub_resValue"></el-input>
          <img
            src="@/assets/img/icon_bianji.png"
            class="ml-1 mr-3"
          />
          <el-button
            type="primary"
            style="visibility: hidden"
          >
            {{ t('confirmText') }}
          </el-button>
        </div>

        <div
          class="bottom flexsc nowrap"
          style="margin-top: 2px"
        >
          <div style="visibility: hidden">{{ t('dockRepair.step2page.valve.res2') }}：</div>
          <el-input v-model="sub_resValue2"></el-input>
          <img
            src="@/assets/img/icon_bianji.png"
            class="ml-1 mr-3"
          />
          <el-button
            type="primary"
            style="visibility: hidden"
          >
            {{ t('confirmText') }}
          </el-button>
        </div>
      </el-form>
    </div>

    <template #footer>
      <div class="dialog-footer flexcc">
        <el-button
          color="#252628"
          plain
          @click="cancel"
        >
          {{ t('cancelText') }}
        </el-button>
        <el-button
          :disabled="activeStep === 0"
          type="primary"
          color="#252628"
          @click="confirm()"
        >
          {{ t('confirmText') }}
        </el-button>
        <el-button
          v-if="activeStep === 1"
          type="primary"
          color="#252628"
          @click="confirm(true)"
        >
          {{ t('dockRepair.step2page.pipeline.b1') }}
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, nextTick, watch, onBeforeMount, computed } from 'vue'
import { useI18n } from 'vue-i18n'
import { insertAddOnApi, finishOrderInsertAddOnApi, getAddOnSteelworkAboutApi } from '@/service/dockOrder'
import useDockRepair from '@/stores/dockRepair.js'
import zh from '@/lang/zh.json'
import en from '@/lang/en.json'

const { t, locale } = useI18n()
const store = useDockRepair()

onBeforeMount(() => {
  getOptions()
})

const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false
  },
  checkedRow: {
    type: Object,
    default: () => null
  },
  isFinishOrder: {
    type: Boolean,
    default: false
  }
})

const emit = defineEmits(['update:modelValue', 'getData'])

const handleClose = () => {
  emit('update:modelValue', false)
}

// 取消
const cancel = () => {
  handleClose()
}

//
const activeStep = ref(0)
const activeName = ref(null)
const tabData = ref([])
const tabChange = (val) => {
  s1ActiveList.value = []
  s2ActiveList.value = []
}
const s1 = computed(() => {
  return tabData.value[activeName.value]?.detailNoOne
})
const s2 = computed(() => {
  return tabData.value[activeName.value]?.detailPlace
})

const getOptions = () => {
  getAddOnSteelworkAboutApi({
    // shipType: store.orderInfo.shcwShippingVo.shippingType
  }).then(({ data }) => {
    tabData.value = data
    activeName.value = 0
  })
}

// 第一步
const s1ActiveList = ref([])
const s2ActiveList = ref([])
const handleSelect = (val, list) => {
  if (activeStep.value === 1) return
  const index = list.findIndex((item) => item === val)
  if (index !== -1) {
    list.splice(index, 1)
  } else {
    list.push(val)
  }
}
const resValue = ref('') // 第一语言
const resValue2 = ref('') // 第二语言
watch(
  [activeName, s1ActiveList, s2ActiveList],
  ([activeName, s1ActiveList, s2ActiveList]) => {
    try {
      const fn = (key, lang, zh, en) => {
        const s = ' '
        const active = tabData.value[activeName][key]
        const s1ActiveListName = s1ActiveList.map((item) => s1.value[item][key])
        const s2ActiveListName = s2ActiveList.map((item) => s2.value[item][key])

        const str = `${active}${s}${s1ActiveListName.join(s)}${s}${s2ActiveListName.join(s)}${s}${eval(`${lang}.dockRepair.step2page.steelStructure.r1`)}`

        return str
      }

      const lang_obj = {
        'zh-CN': 'zh',
        en: 'en'
      }
      resValue.value = fn('projectName', lang_obj[locale.value], zh, en)
      if (locale.value === 'zh-CN') {
        resValue2.value = fn('projectNameEn', 'en', zh, en)
      }
      if (locale.value === 'en') {
        resValue2.value = fn('projectNameCn', 'zh', zh, en)
      }
    } catch (error) {
      console.log(error)
    }
  },
  { deep: true }
)

const afterCheckedId = ref(null)
// 下一步
const handleNext = () => {
  const api = !props.isFinishOrder ? insertAddOnApi : finishOrderInsertAddOnApi
  api({
    addOnDetailList: [{ projectName: resValue.value, projectName2: resValue2.value }],
    projectParent: props.checkedRow.id
  }).then(({ data }) => {
    activeStep.value++
    afterCheckedId.value = data
    ElMessage.success(t('saveSuccess'))
    emit('getData')
  })
}

// 第二步
const typeList = ref(['dockRepair.step2page.steelStructure.type1', 'dockRepair.step2page.steelStructure.type2', 'dockRepair.step2page.steelStructure.type3', 'dockRepair.step2page.steelStructure.type4', 'dockRepair.step2page.steelStructure.type5', 'dockRepair.step2page.steelStructure.type6', 'dockRepair.step2page.steelStructure.type7'])
const activeType = ref({})
const handleSelect_type = (val, index) => {
  if (activeStep.value === 0) return
  activeType.value = { val, index }
  activeModel.value = []
  formData.value = {}
  requireCount.value = null
  sub_resValue.value = ''
}

// t('dockRepair.step2page.steelStructure.m3')
const modelList = ref([
  {
    val: 'dockRepair.step2page.steelStructure.m5',
    isT: true
  },
  {
    val: 'AH32',
    isT: false
  },
  {
    val: 'AH36',
    isT: false
  },
  {
    val: 'dockRepair.step2page.steelStructure.m3',
    isT: true
  },
  {
    val: 'dockRepair.step2page.steelStructure.m4',
    isT: true
  }
])
const activeModel = ref([])
const handleSelect_model = (val, index) => {
  if (activeStep.value === 0) return
  if (activeModel.value.some((item) => item.index === index)) {
    activeModel.value.splice(
      activeModel.value.findIndex((item) => item.index === index),
      1
    )
  } else {
    activeModel.value.push({ ...val, index })
  }
}

const formData = ref({})
watch(
  formData,
  (n) => {
    if (activeType.value.index === 0) {
      if (!n.aaa || !n.bbb || !n.ccc) return
      requireCount.value = n.aaa * n.bbb * n.ccc * 8
    }
  },
  {
    deep: true
  }
)
const requireCount = ref(null)
const unit = computed(() => {
  if (activeType.value.index === 0) {
    if (requireCount.value > 10) {
      return 'kg'
    }

    if (requireCount.value < 10 || requireCount.value === 10) {
      return 'pc'
    }
  }
  return 'm'
})
const sub_resValue = ref('')
const sub_resValue2 = ref('')

watch(
  [activeType, formData, activeModel, requireCount],
  ([activeType, formData, activeModel, requireCount]) => {
    const lang_obj = {
      'zh-CN': 'en.',
      en: 'zh.'
    }

    try {
      // 钢板
      if (activeType.index === 0) {
        if (!formData.aaa || !formData.bbb || !formData.ccc || !activeModel.length) return
        const modelStr = activeModel.map((item) => (item.isT ? t(item.val) : item.val)).join(' ')
        const modelStr2 = activeModel.map((item) => (item.isT ? eval(lang_obj[locale.value] + item.val) : item.val)).join(' ')
        sub_resValue.value = `${t(activeType.val)}${formData.aaa}mmx${formData.bbb}mx${formData.ccc}m ${modelStr}`
        sub_resValue2.value = `${eval(lang_obj[locale.value] + activeType.val)}${formData.aaa}mmx${formData.bbb}mx${formData.ccc}m ${modelStr2}`
      }

      // '角钢', '方钢','槽钢', '球扁钢'
      if ([1, 2, 5, 6].includes(activeType.index)) {
        if (!formData.aaa || !formData.bbb || !requireCount) return
        sub_resValue.value = `${t(activeType.val)} ${formData.aaa} x ${formData.bbb}mm x ${requireCount}m`
        sub_resValue2.value = `${eval(lang_obj[locale.value] + activeType.val)} ${formData.aaa} x ${formData.bbb}mm x ${requireCount}m`
      }

      // '圆钢', '钢管'
      if ([3, 4].includes(activeType.index)) {
        if (!formData.aaa || !requireCount) return
        sub_resValue.value = `${t(activeType.val)} ${formData.aaa}mm x ${requireCount}m`
        sub_resValue2.value = `${eval(lang_obj[locale.value] + activeType.val)} ${formData.aaa}mm x ${requireCount}m`
      }
    } catch (error) {
      console.log(error)
    }
  },
  {
    deep: true
  }
)

// 重置
const reset = () => {
  activeStep.value = 0
  getOptions()
  s1ActiveList.value = []
  s2ActiveList.value = []
  resValue.value = ''
  activeType.value = {}
  activeModel.value = []
  formData.value = {}
  requireCount.value = null
  afterCheckedId.value = null
}

// 确定
const confirm = (isContinue = false) => {
  // console.log(unit.value, requireCount.value)
  const api = !props.isFinishOrder ? insertAddOnApi : finishOrderInsertAddOnApi
  api({
    addOnDetailList: [
      {
        projectName: sub_resValue.value,
        projectName2: sub_resValue2.value,
        requireCount: requireCount.value,
        unit: unit.value,
        unit2: unit.value
      }
    ],
    projectParent: afterCheckedId.value
  }).then(() => {
    ElMessage.success(t('saveSuccess'))
    emit('getData')

    if (isContinue) {
      reset()
    } else {
      handleClose()
    }
  })
}
</script>

<style scoped lang="scss">
.title {
  font-weight: bold;
  color: #252628;
  &::before {
    content: '';
    display: inline-block;
    width: 4px;
    height: 12px;
    background: var(--mainColor);
    margin-right: 8px;
  }
}
.select {
  .item {
    .li {
      padding: 5px 10px;
      cursor: pointer;
      margin-top: 10px;
      background: #fae9e5;

      &.active {
        background: var(--mainColor);
        color: #fff;
        border-color: var(--mainColor);
      }
    }
  }
}

.main {
  padding: 20px;
  background: #f9f9f9;

  .form {
    .item {
      margin-bottom: 10px;
      display: grid;
      grid-template-columns: 30px auto auto;
      gap: 10px;
    }

    &.type1 {
      padding-right: 100px;
      .grid-4 {
        grid-template-columns: auto auto auto 220px;
        gap: 30px;
      }
      .item {
        grid-template-columns: 30px auto auto;
        .el-input-number {
          width: 100%;
        }
      }
    }
  }

  &.en {
    .form {
      .item {
        grid-template-columns: 70px auto auto;
        .label {
          text-align: right;
        }
      }

      &.type1 {
        padding-right: 120px;
        .grid-4 {
          gap: 20px;
        }
      }
    }
  }
}
</style>
